/*
 * Copyright (c) 2012-2014, EpicSaaS Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package com.epicsaas.app.ksdapp.controller.phone;

import com.epicpaas.sdk.core.api.logging.Logger;
import com.epicpaas.sdk.core.api.logging.LoggerFactory;
import com.epicpaas.sdk.core.api.ServiceResult;
import com.epicsaas.framework.util.DateTimeUtils;
import com.epicsaas.app.ksdapp.common.MVCViewName;
import com.epicsaas.app.ksdapp.dao.customized.CartItemCustomziedMapper;
import com.epicsaas.app.ksdapp.entity.gen.CartCriteria;
import com.epicsaas.app.ksdapp.entity.gen.CartItemCriteria;
import com.epicsaas.app.ksdapp.service.ICartItemService;
import com.epicsaas.app.ksdapp.service.ICartService;
import com.epicsaas.app.ksdapp.service.IProductService;
import com.epicsaas.app.ksdapp.android.bean.Cart;
import com.epicsaas.app.ksdapp.android.bean.CartItem;
import com.epicsaas.app.ksdapp.android.bean.Product;
import com.epicsaas.app.ksdapp.android.bean.Product.SpecificationValues;
import com.epicsaas.app.ksdapp.appobject.CartAO;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import javax.validation.Valid;

import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Cart控制器。
 * 
 */
@Controller
@RequestMapping(value = "/phone/cart")
public class CartController {

    private static Logger LOG = LoggerFactory.getLogger(CartController.class);

    @Resource
    private ICartService cartService;

    @Resource
    private IProductService productService;

    @Resource
    private ICartItemService cartItemService;

    /**  9.2获取购物车详情 */
    @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Cart cart(String userid, String token, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        float allprice = 0, allitemOldPrice = 0;
        int chosenQuantity = 0;
        Cart cart = new Cart();
        List<CartItem> cartItems = new ArrayList<CartItem>();
        CartItemCriteria example = new CartItemCriteria();
        example.createCriteria().andUserIdEqualTo(Integer.parseInt(userid));
        ServiceResult<List<CartItem>> cartItemListRet = cartItemService.selectByCriteria(example);
        LOG.info("line 79 cartItemListRet [%s]", cartItemListRet);
        if (cartItemListRet.isSucceed() && !CollectionUtils.isEmpty(cartItemListRet.getData())) {
            for (CartItem cartItem : cartItemListRet.getData()) {
                List<Product> pListRet = productService.getProductsByShopidAndShopitemid(String.valueOf(cartItem
                        .getShopId()), String.valueOf(cartItem.getShopItemId()));
                if (null != pListRet && pListRet.size() > 0) {
                    float price = 0, itemOldPrice = 0;
                    cartItem.setChosen(true);
                    cartItem.setValid(true);
                    price += cartItem.getQuantity() * cartItem.getItemPayPrice();

                    cartItem.setItemPayPrice(price);
                    itemOldPrice += cartItem.getQuantity() * cartItem.getItemOldPrice();
                    cartItem.setItemOldPrice(itemOldPrice);
                    cartItem.setItem(pListRet.get(0));
                    if (cartItem.isChosen()) {
                        chosenQuantity++;
                        allprice += price;
                        allitemOldPrice += itemOldPrice;
                    }

                }
                cartItems.add(cartItem);
            }
        }

        cart.setCartItems(cartItems);
        cart.setPrice(allprice);
        cart.setToken(token);
        //cart.setWeight(1002);
        cart.setItemOldPrice(allitemOldPrice);
        cart.setAllQuantity(cartItems.size());
        cart.setChosenQuantity(chosenQuantity);
        LOG.info("line 111 cart [%s]", cart.toString());
        return cart;
    }

    /** 9.3添加特卖商品     v2中不包含*/
    @RequestMapping(value = "/addSpecialSale", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object addSpecialSale(Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(), DateTimeUtils.FORMAT_YMD_HMS));
        //将当前运用名称传到前端

        ModelAndView mv = new ModelAndView();
        mv.addObject(model);

        return mv;
    }

    /** 9.4添加团购商品   v2中不包含*/
    @RequestMapping(value = "/addGroupBuy", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object addGroupBuy(Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(), DateTimeUtils.FORMAT_YMD_HMS));
        //将当前运用名称传到前端

        ModelAndView mv = new ModelAndView();
        mv.addObject(model);

        return mv;
    }

    /** 9.5 添加普通商品到购物车 */
    @RequestMapping(value = "/addProduct", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object addProduct(String userid, String token, String id, int quantity, String promotionType, Model model,
            HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());

        System.out.println("userid=" + userid + ",ShopItemId=" + id);
        ServiceResult<Boolean> ret = new ServiceResult<Boolean>();

        CartAO entityAO = new CartAO();

        CartCriteria example = new CartCriteria();
        example.createCriteria().andUserIdEqualTo(userid).andShopItemIdEqualTo(Integer.parseInt(id));
        LOG.info("userid=[%s],ShopItemId=[%s]", userid, id);
        ServiceResult<List<CartAO>> retListCartAO = cartService.selectByCriteria(example);
        LOG.info("line 163 retListCartAO [%s]", retListCartAO);
        if (retListCartAO.isSucceed() && !CollectionUtils.isEmpty(retListCartAO.getData())) {
            entityAO = retListCartAO.getData().get(0);
            entityAO.setCount(entityAO.getCount() + quantity);
            ret = cartService.update(entityAO);
            LOG.info("line 169 ret  [%s]", ret);

        } else {

            entityAO.setCount(quantity);
            entityAO.setChosen(1);
            entityAO.setUserId(userid);
            entityAO.setShopItemId(Integer.parseInt(id));
            entityAO.setCreateTime(new Date());
            entityAO.setStatus(1);
            ret = cartService.save(entityAO);
            LOG.info("line 180 ret  [%s]", ret);
        }
        LOG.info("line 181 ret  [%s]", ret);
        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        LOG.info("line 192 cart [%s]", cart.toString());
        return cart;
    }

    /** 9.6添加多个普通商品  */
    @RequestMapping(value = "/addProducts", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object addProducts(long[] ids, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());

        Cart cart = new Cart();

        return cart;
    }

    /** 9.7添加组合套餐 */
    @RequestMapping(value = "/addProductMeal", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object addProductMeal(long id, int quantity, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        Cart cart = new Cart();

        return cart;
    }

    /** 9.8编辑购物车项的购买数量 */
    /**
     * 
     * @param id 商品ID
     * @param quantity 增加的商品数量
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object edit(String userid, String token, long id, int quantity, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());

        CartAO entityAO = cartService.getById(String.valueOf(id)).getData();
        entityAO.setCount(quantity);
        ServiceResult<Boolean> ret = cartService.update(entityAO);
        LOG.info("line 238 ret  [%s]", ret);
        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        LOG.info("line 249 cart [%s]", cart.toString());
        return cart;
    }

    /** 9.9选中购物车项  */
    @RequestMapping(value = "/select", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object select(String userid, String token, String[] ids, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        ServiceResult<Boolean> ret = new ServiceResult<Boolean>();
        CartCriteria example = new CartCriteria();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        ServiceResult<List<CartAO>> entityAORet = cartService.selectByCriteria(example);
        if (entityAORet.isSucceed() && !CollectionUtils.isEmpty(entityAORet.getData())) {
            for (CartAO cartAO : entityAORet.getData()) {
                cartAO.setChosen(1);
                ret = cartService.update(cartAO);
            }
        }

        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        return cart;
    }

    /** 9.10  取消选中购物车项 */
    @RequestMapping(value = "/unselect", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object unselect(String userid, String token, String[] ids, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        ServiceResult<Boolean> ret = new ServiceResult<Boolean>();
        CartCriteria example = new CartCriteria();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        ServiceResult<List<CartAO>> entityAORet = cartService.selectByCriteria(example);
        if (entityAORet.isSucceed() && !CollectionUtils.isEmpty(entityAORet.getData())) {
            for (CartAO cartAO : entityAORet.getData()) {
                cartAO.setChosen(0);
                ret = cartService.update(cartAO);
            }
        }

        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        return cart;
    }

    /** 9.11  删除购物车项  */
    @RequestMapping(value = "/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object deleteById(String userid, String token, String id, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        ServiceResult<Boolean> ret = cartService.deleteById(id);
        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        return cart;
    }

    /**  9.12  清空购物车  */
    @RequestMapping(value = "/clear", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object clear(String userid, String token, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        CartCriteria criteria = new CartCriteria();
        criteria.createCriteria().andUserIdEqualTo(userid);
        ServiceResult<Boolean> ret = cartService.deleteByCriteria(criteria);
        if (ret.isSucceed() && ret.getData()) {
            return cart(userid, token, model, request);
        }
        Cart cart = new Cart();
        cart.setAllQuantity(0);
        cart.setCartItems(null);
        cart.setWeight(0);
        cart.setToken(token);
        cart.setPrice(0);
        cart.setItemOldPrice(0);
        return cart;
    }

    /**    9.13 购物车商品数量   */
    @RequestMapping(value = "/cartProductQuantity", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object cartProductQuantity(String userid, String token, Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        return cart(userid, token, model, request);
    }

}
